//
//  ProjectDetialViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/16.
//

import UIKit
import UITableView_FDTemplateLayoutCell
import Kingfisher
import PKHUD
import MJRefresh

/// 项目详细界面
class ProjectDetialViewController: BaseViewController {

    var detialTableView:UITableView!
    var headerCellID = "projectdetialheadcell"
    var ownerCellID = "projectdetialownercell"
    var normalCellID = "projectnormalcell"
    
    let cellTitles = ["Readme","代码","问题","提交"]
    let cellImages = ["projectDetails_readme","projectDetails_code","projectDetails_issue","projectDetails_branch"]
    
    var projectM:ProjectMdoel? {
        didSet{
            guard let _ = projectM else { return }
            self.detialTableView.reloadData()
        }
    }
    
    // 初始化使用的model 要在去跟进id查询下 防止其他端修改了内容么有同步
    var _project:ProjectMdoel?
    init(project: ProjectMdoel) {
        super.init(nibName: nil, bundle: nil)
        self._project = project
        self.title = _project?.name
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
}

// MARK: - 设置界面
extension ProjectDetialViewController {
    
    func setupUI(){
        
        var frame = view.bounds
        frame.size.height -= Common.topHeight
        self.detialTableView = UITableView(frame: frame)
        self.detialTableView.separatorStyle = .none
        self.detialTableView.register(UINib(nibName: "ProjectDeitalHeaderTableViewCell", bundle: nil), forCellReuseIdentifier: headerCellID)
        self.detialTableView.register(UINib(nibName: "ProjectOwnerTableViewCell", bundle: nil), forCellReuseIdentifier: ownerCellID)
        //
        self.detialTableView.register(UINib(nibName: "ProjectNormalTableViewCell", bundle: nil), forCellReuseIdentifier: normalCellID)
//        self.detialTableView.register(UITableViewCell.self, forCellReuseIdentifier: footerCellID)
        self.detialTableView.delegate = self
        self.detialTableView.dataSource = self
        view.addSubview(self.detialTableView)
        
        let mjHeader = MJRefreshNormalHeader {
            self.loadData()
        }
        mjHeader?.lastUpdatedTimeLabel.isHidden = true
        self.detialTableView.mj_header = mjHeader
        mjHeader?.beginRefreshing()
        
        if #available(iOS 13.0, *) {
            detialTableView.backgroundColor = Colors.backgroundColor
        }
    }
}

// MARK: - 加载数据
extension ProjectDetialViewController {
    
    func loadData(){
        
        guard let p = _project else {
            self.detialTableView.mj_header.endRefreshing()
            return
        }
        
        DispatchQueue.global().async {
            let url = URLs.DETIAL_URL + p.id.description //+ "?private_token=Eeu8RUV6SgCacx3U45UP"
            let result:Result<ProjectMdoel> = NetWorkTool.shared.getRequest(url: url, parameters: nil)
            DispatchQueue.main.async {
                self.detialTableView.mj_header.endRefreshing()
                if result.code == 0 {
                    self.projectM = result.data
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
            }
        }
    }
}

// MARK: - tableview delegate datasource
extension ProjectDetialViewController:UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        6
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 拥有者
        if indexPath.row == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: ownerCellID, for: indexPath) as! ProjectOwnerTableViewCell
            cell.model = projectM
            return cell
        }
        // 项目描述等内容
        else if indexPath.row == 1 {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: headerCellID, for: indexPath) as! ProjectDeitalHeaderTableViewCell
            cell.model = projectM
            cell.selectionStyle = .none
            cell.delegate = self
            return cell
        }else {
            // 其他内容
            let cell = tableView.dequeueReusableCell(withIdentifier: normalCellID, for: indexPath) as! ProjectNormalTableViewCell
            cell.cellImageView.image = UIImage(named: cellImages[indexPath.row-2])
            cell.cellNameLabel.text = cellTitles[indexPath.row - 2]
        
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.row == 1 {
            return tableView.fd_heightForCell(withIdentifier: headerCellID) { (cell) in
                
                (cell as! ProjectDeitalHeaderTableViewCell).model = self.projectM
                (cell as! ProjectDeitalHeaderTableViewCell).selectionStyle = .none
                
            }
        }
        if indexPath.row == 0 {
            return tableView.fd_heightForCell(withIdentifier: ownerCellID) { (cell) in
                
                (cell as! ProjectOwnerTableViewCell).model = self.projectM
                (cell as! ProjectOwnerTableViewCell).selectionStyle = .none
            }
        }
        
        return 55
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch indexPath.row {
        case 0: // 拥有者
            self.navigationController?.pushViewController(OtherPersonHomeViewController(model: projectM?.owner, titles: ["动态","项目","Star","Watch"]), animated: true)
        case 2: // readme
            self.navigationController?.pushViewController(ReadMeViewController(pid: self.projectM!.id), animated: true)
        case 3: // 代码
            self.navigationController?.pushViewController(TableCodeTreeViewController(project: self.projectM!,path: ""), animated: true)
        case 4:// 问题
            self.navigationController?.pushViewController(IssueListViewController(project: self.projectM!), animated: true)
        case 5:// 提交
            self.navigationController?.pushViewController(CommitsViewController(project: self.projectM!), animated: true)
        default:// 项目介绍 不可点击
            print("项目介绍 不可点击")
        }
    }
    
}

// MARK: - watch 和 star 安努点击
extension ProjectDetialViewController:ProjectDeitalHeaderTableViewCellDelegate {
    
    func starButtonClick() {
        
        if !loginCommand() {return}
        
        HUD.show(.progress)
        let stared:Bool = self.projectM!.stared
        let watchStr = stared ? "unstar" : "star"
        let nameSpace = self.projectM!.path_with_namespace!
        let nameSpaceStr = nameSpace.replacingOccurrences(of: "/", with: "%2F")
        
        DispatchQueue.global().async {
            let url = URLs.V3URL + URLs.PROJECTS + nameSpaceStr + "/" + watchStr
            
            let result:Result<WatchStarResultModel> = NetWorkTool.shared.getRequest(url: url,method: .post)
            DispatchQueue.main.async {
                HUD.hide()
                if result.code == 0 {
                    guard let countM = result.data else {
                        HUD.flash(.label("操作失败"), delay: 1.0)
                        return
                    }
                    self.projectM?.stared = !stared
                    self.projectM?.stars_count = countM.count
                    self.detialTableView.reloadData()
                }else {
                    HUD.flash(.label(result.message), delay: 1.0)
                }
            }
        }
    }
    
    func watchButtonClik() {
        if !loginCommand() {return}
        
        HUD.show(.progress)
        let watched:Bool = self.projectM!.watched
        let watchStr = watched ? "unwatch" : "watch"
        let nameSpace = self.projectM!.path_with_namespace!//.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
        let nameSpaceStr = nameSpace.replacingOccurrences(of: "/", with: "%2F")
        
        DispatchQueue.global().async {
            let url = URLs.V3URL + URLs.PROJECTS + nameSpaceStr + "/" + watchStr
            let result:Result<WatchStarResultModel> = NetWorkTool.shared.getRequest(url: url,method: .post)
            DispatchQueue.main.async {
                HUD.hide()
                if result.code == 0 {
                    
                    guard let countM = result.data else {
                        HUD.flash(.label("操作失败"), delay: 1.0)
                        return
                    }
                    self.projectM?.watched = !watched
                    self.projectM?.watches_count = countM.count
                    self.detialTableView.reloadData()
                }else {
                    HUD.flash(.label(result.message), delay: 1.0)
                }
            }
        }
    }
    
    func loginCommand()->Bool{
        
        if UserDefaultTools.getToken() == nil {
            let vc = LoginViewController()
            vc.title = "登陆"
            let loginVC = BaseNavigationController(rootViewController: vc)
            loginVC.modalPresentationStyle = .fullScreen
            if #available(iOS 13.0, *) {
                loginVC.isModalInPresentation = true
            }
            self.present(loginVC, animated: true, completion: nil)
            return false
        }else {
            return true
        }
    }
}
